package com.gzzyy.unionchain.ui.business.login

import android.os.Bundle
import android.util.Log
import android.view.View
import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.ToastUtils
import com.gzzyy.unionchain.App
import com.gzzyy.unionchain.LiveEvent
import com.gzzyy.unionchain.data.ObjectBox
import com.gzzyy.unionchain.databinding.ActivityCreateWalletBinding
import com.gzzyy.unionchain.ui.base.BaseActivity
import com.gzzyy.unionchain.ui.business.main.MainActivity
import com.gzzyy.unionchain.util.KeyUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class CreateWalletActivity : BaseActivity() {

    private var dataSyncingEnd = false

    private lateinit var binding: ActivityCreateWalletBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCreateWalletBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.toolbar.setNavigationOnClickListener { finish() }
        binding.confirmBtn.setOnClickListener {
            val safePwd = binding.safePwdEt.text.toString()
            val safePwd2 = binding.safePwd2Et.text.toString()
            if (safePwd.length in 8..32) {
                if (safePwd == safePwd2) {
                    if (dataSyncingEnd) {
                        binding.confirmBtn.isEnabled = false
                        createWallet(safePwd)
                    } else {
                        ToastUtils.showShort("数据同步中，请稍后再试")
                    }
                } else {
                    ToastUtils.showShort("两次输入密码不一致，请核对密码")
                }
            } else {
                ToastUtils.showShort("密码长度需8到32位，请输入合适的密码")
            }
        }

        LiveEventBus.get(LiveEvent.GetTransferListEnd).observeStickyForever {
            dataSyncingEnd = true
            binding.dataSyncingTv.visibility = View.GONE
        }
    }

    private fun createWallet(safePwd: String) {
        GlobalScope.launch {
            val pair = KeyUtil.generateUserKey(safePwd)
            App.user = pair.first
            App.tripleKey = pair.second
            Log.e("test", "walletAddress = ${App.user?.walletAddress}")
            val transferObj = combineSystemTransferBean()
            Log.e("test", "after transferObj ")
            LiveEventBus.get(LiveEvent.CommitTransfer).post(transferObj)
            withContext(Dispatchers.Main) {
                ToastUtils.showShort("钱包生成成功")
                startActivity(MainActivity::class.java)
                finish()
                Log.e("test", "after finish ")
            }
        }
    }

    private fun combineSystemTransferBean(): JSONObject {
        val transferBeanBox = ObjectBox.getRecordBox()
        val preHash = KeyUtil.findPreHash(transferBeanBox)
        val nonce = UUID.randomUUID().toString()
        val createTime = (System.currentTimeMillis() / 1000).toString()
        val hash = KeyUtil.getTransferHash(preHash, nonce, createTime)
        return KeyUtil.combineTransferBean(
            "system0000001",
            App.user?.walletAddress,
            100f,
            100f,
            100f,
            nonce,
            preHash,
            transferBeanBox.all.size,
            hash,
            KeyUtil.getTransferHashSign(hash),
            createTime
        )
    }

}